<template>
  <div>
    <div class="content">
      <el-row :gutter="40">
        <el-col :span="4">
          <div class="box">
            <el-collapse v-model="activeNames">
              <el-collapse-item name="1">
                <template #title>
                  <span style="font-size: 18px">通用方法</span>
                </template>
                <div class="btn-list">
                  <div
                    :class="['btn', currentMethodIndex == 'module1' + index ? 'active' : '']"
                    v-for="(item, index) in module1"
                    :key="index"
                    @click="handleModule1(item, index)"
                  >
                    {{ item.name }}
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
          <div class="box mt-4">
            <el-collapse>
              <el-collapse-item title="数据处理" name="2">
                <template #title>
                  <span style="font-size: 18px">数据处理</span>
                </template>
                <div class="btn-list">
                  <div class="btn">标题处理</div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
          <div class="box mt-4">
            <el-collapse>
              <el-collapse-item title="综合评价" name="3">
                <template #title>
                  <span style="font-size: 18px">综合评价</span>
                </template>
                <div class="btn-list">
                  <div
                    :class="['btn', currentMethodIndex == 'module2' + index ? 'active' : '']"
                    v-for="(item, index) in module2"
                    :key="index"
                    @click="handleModule2(item, index)"
                  >
                    {{ item.name }}
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </el-col>
        <el-col :span="20" v-loading="loading">
          <div class="box tabs">
            <el-tag
              class="tab"
              v-for="item in methodList"
              :key="item.id"
              closable
              size="large"
              @close="handleTagClose(item)"
              @click="handleTagClick(item)"
              :effect="item.id == currentMethod.id ? 'dark' : ''"
            >
              {{ item.name }}
              <span style="position: absolute; right: 30px; bottom: 0">{{ item.index }}</span>
              <span class="tag-edit" style="position: absolute; left: 10px; top: 7px">
                <el-icon @click.stop="handleEditName(item)"><Edit /></el-icon>
              </span>
            </el-tag>
          </div>
          <Board v-show="!showResult && currentMethod" @startAnalysis="startAnalysis" :analysisMethod="currentMethod" />
          <Result v-if="showResult" @back="back" :data="currentResult" :analysisMethod="currentMethod" />
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { Edit } from '@element-plus/icons-vue'
import ExcelJS from 'exceljs'
import Header from './components/Header.vue'
import Board from './components/Board.vue'
import Result from './components/Result.vue'
import { onMounted } from 'vue-demi'
import {
  dataAnalysisList,
  dataAnalysisSave,
  dataAnalysisDel,
  dataAnalysisUpdate,
  dataAnalysisInfo,
  dataAnalysisSetName
} from '@/api/analysis'
import { ElInput, ElMessage, ElMessageBox } from 'element-plus'
const showResult = ref(false)
const loading = ref(false)
const currentResult = ref('')
const activeNames = ref('1')
const methodList = ref([])
const currentMethod = ref('')
const currentMethodIndex = ref('')
const module1 = ref([
  {
    name: '交叉(卡方)',
    value: 'Chi-Square',
    x: 1,
    y: 9999,
    xLabel: 'X(定类)',
    yLabel: 'Y(定类)'
  },
  {
    name: '方差',
    value: 'variance',
    x: 1,
    y: 9999,
    xLabel: 'X(定类)',
    yLabel: 'Y(定量)'
  },
  {
    name: '频数',
    value: 'frequency',
    x: 0,
    y: 9999,
    yLabel: '分析项(定类)'
  },
  {
    name: '正态性检验',
    value: 'normalityTest',
    x: 9999,
    y: 1,
    xLabel: '分析项(定类)',
    yLabel: '分组项【可选】'
  },
  {
    name: '配对t检验',
    value: 'TTestPaired',
    x: 9999,
    y: 9999,
    xLabel: '配对1(定量)',
    yLabel: '配对2(定量)'
  },
  {
    name: '单样本t检验',
    value: 'TTestSingle',
    x: 0,
    y: 9999,
    yLabel: '分析项(定类)'
  },
  {
    name: 't检验',
    value: 'TTest',
    x: 1,
    y: 9999,
    xLabel: 'X(定类，仅两组)',
    yLabel: 'Y(定量)'
  }
])
const module2 = ref([
  {
    name: '灰色关联法',
    value: 'gray',
    x: 9999,
    y: 1,
    xLabel: '特征序列(评价项)',
    yLabel: '参考值(母序列)【可选】'
  }
])
const startAnalysis = async (data, params) => {
  loading.value = true
  dataAnalysisInfo(currentMethod.value._id)
    .then((res) => {
      currentMethod.value = res.data
      currentResult.value = res.data.data
      setStorage()
      showResult.value = true
    })
    .finally(() => {
      loading.value = false
    })
}
const back = () => {
  showResult.value = false
}
const handleModule1 = (item, index) => {
  showResult.value = false
  const params = {
    ...item,
    id: new Date().getTime()
  }
  currentMethod.value = params
  // methodList.value.push(params)
  currentMethodIndex.value = 'module1' + index
  setStorage()
}
const handleModule2 = (item, index) => {
  showResult.value = false
  const params = {
    ...item,
    id: new Date().getTime()
  }
  currentMethod.value = params
  // methodList.value.push(params)
  currentMethodIndex.value = 'module2' + index
  setStorage()
}
const handleTagClose = (item) => {
  loading.value = true
  const method = methodList.value.find((i) => i.id == item.id)
  dataAnalysisDel(method._id)
    .then((res) => {
      showResult.value = false
      getStorage()
    })
    .then((res) => {
      loading.value = false
    })
  // methodList.value.splice(index, 1)
  // if (item.id == currentMethod.value.id) {
  //   currentMethod.value = methodList.value[0] || ''
  // }
  // setStorage()
}
const handleTagClick = (item) => {
  showResult.value = false
  loading.value = true
  dataAnalysisInfo(item._id)
    .then((res) => {
      currentMethod.value = res.data
      currentResult.value = res.data.data
      if (res.data.data) {
        showResult.value = true
      } else {
        showResult.value = false
      }
      setStorage()
    })
    .then((res) => {
      loading.value = false
    })
  // if (item.params && item.data) {
  //   currentResult.value = currentMethod.value.data
  //   showResult.value = true
  // } else {
  //   showResult.value = false
  // }
  // setStorage()
}
const setStorage = async () => {
  loading.value = true
  const params = {
    ...currentMethod.value,
    finalUpdateTime: new Date().getTime()
  }
  if (params._id) {
    await dataAnalysisUpdate(params).then((res) => {
      loading.value = false
    })
  } else {
    await dataAnalysisSave(params).then((res) => {
      getStorage()
    })
  }

  // localStorage.setItem('methodList', JSON.stringify(methodList.value))
  // localStorage.setItem('currentMethod', JSON.stringify(currentMethod.value))
}
const getStorage = () => {
  loading.value = true
  dataAnalysisList()
    .then((res) => {
      methodList.value = res.data
      if (res.data.length == 0) {
        currentMethod.value = ''
        return
      }
      // 查找最后更新时间最大的
      const maxItem = methodList.value.reduce((prev, current) => {
        return prev.finalUpdateTime > current.finalUpdateTime ? prev : current
      })
      // currentMethod.value = maxItem
      dataAnalysisInfo(maxItem._id)
        .then((res) => {
          currentMethod.value = res.data

          if (res.data.data) {
            currentResult.value = res.data.data
            showResult.value = true
          } else {
            showResult.value = false
          }
        })
        .finally(() => {
          loading.value = false
        })
      // if (maxItem.data) {
      //   currentResult.value = maxItem.data
      //   showResult.value = true
      // }
    })
    .finally(() => {
      loading.value = false
    })
  // const methodListStr = localStorage.getItem('methodList')
  // const currentMethodStr = localStorage.getItem('currentMethod')
  // if (methodListStr) {
  //   methodList.value = JSON.parse(methodListStr)
  // }
  // if (currentMethodStr) {
  //   currentMethod.value = JSON.parse(currentMethodStr)
  //   if (currentMethod.value.data) {
  //     currentResult.value = currentMethod.value.data
  //     showResult.value = true
  //   }
  // }
}
const editName = ref('')
const handleEditName = (item) => {
  console.log(item)

  editName.value = item.name
  ElMessageBox({
    title: '重命名',
    // Should pass a function if VNode contains dynamic props
    message: () =>
      h(ElInput, {
        modelValue: editName.value,
        'onUpdate:modelValue': (val) => {
          editName.value = val
        }
      })
  }).then(() => {
    console.log(editName.value)
    dataAnalysisSetName(item._id, editName.value).then((res) => {
      ElMessage.success('重命名成功')
      getStorage()
    })
  })
}
onMounted(() => {
  // 默认第一个
  // handleModule1(module1.value[0], 0)
  getStorage()
  setTimeout(() => {
    // exportExcel()
  }, 2000)
})

//下载文件
const download_file = (buffer, fileName) => {
  console.log('导出')
  let fileURL = window.URL.createObjectURL(new Blob([buffer]))
  let fileLink = document.createElement('a')
  fileLink.href = fileURL
  fileLink.setAttribute('download', fileName)
  document.body.appendChild(fileLink)
  fileLink.click()
}
const exportExcel = async () => {
  const workbook = new ExcelJS.Workbook()
  const worksheet = workbook.addWorksheet('Sheet1')
  //这里是数据列表
  const data = [
    { id: 1, name: '艾伦', age: 20, sex: '男', achievement: 90 },
    { id: 2, name: '柏然', age: 25, sex: '男', achievement: 86 },
    { id: 3, name: '程丽', age: 30, sex: '女', achievement: 90 }
  ]
  // 设置列,这里的width就是列宽
  worksheet.columns = [
    { header: '序号', key: 'id', width: 10 },
    { header: '姓名', key: 'name', width: 10 },
    { header: '年龄', key: 'age', width: 10 }
  ]

  // 批量插入数据
  data.forEach((item) => worksheet.addRow(item))
  //设置行高,因为第一行被表头占据了,所以从2开始,也就是数据的第一行
  //想设置其他行设置参数就好了
  worksheet.getRow(2).height = 30
  // 合并单元格,就是把B1开始到D1的单元格合并
  worksheet.mergeCells('B1:D1')
  //设置样式表格样式,font里面设置字体大小,颜色(这里是argb要注意),加粗
  //alignment 设置单元格的水平和垂直居中
  const B1 = worksheet.getCell('B1')
  B1.font = { size: 20, color: { argb: 'FF8B008B' }, bold: true }
  B1.alignment = { horizontal: 'center', vertical: 'middle' }
  // 写入文件
  const buffer = await workbook.xlsx.writeBuffer()
  //下载文件
  download_file(buffer, '填报汇总.xlsx')
}
</script>

<style lang="scss" scoped>
.content {
  .box {
    padding: 0 10px;
    background-color: #fff;
    box-shadow: 0 0 5px #ccc;
    border-radius: 5px;
  }
  .board {
    height: calc(100vh - 166px);
    padding: 10px 20px;
  }
  .tabs {
    // height: 50px;
    margin-bottom: 1rem;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    overflow: auto;
    padding: 10px;
    .tab {
      .tag-edit {
        display: none;
      }
      &:hover {
        .tag-edit {
          display: block;
        }
      }
    }
    .el-tag {
      cursor: pointer;
      min-width: 140px;
      position: relative;
      margin-right: 10px;
      margin-bottom: 10px;
      :deep(.el-tag__close) {
        position: absolute;
        right: 10px;
      }
    }
  }
  .btn-list {
    display: flex;
    flex-wrap: wrap;
    .btn {
      background-color: #fafafa;
      color: #000;
      width: 45%;
      margin: 10px 2.5%;
      height: 40px;
      border: 1px solid #ccc;
      border-radius: 10px;
      line-height: 40px;
      text-align: center;
      cursor: pointer;
      transition: all 0.3s;
      &:hover {
        background-color: #178aec;
        color: #fff;
      }
    }
    .active {
      background-color: #178aec;
      color: #fff;
    }
  }
}
:deep(.el-collapse-item__content) {
  padding-bottom: 0;
}
</style>
